package com.aaa.sso.util;

import com.aaa.common.bo.User;
import com.aaa.sso.service.RemoteUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @fileName:UserRealm
 * @description:
 * @author:zhz
 * @createTime:2020/12/7 10:53
 * @version:1.0.0
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       //获取登录会员信息 (用户名)
        String userName = (String)authenticationToken.getPrincipal();
        //调用远程接口 获取会员信息
        User user = remoteUserService.queryByUserName(userName);
        //判断member 是否为空 为空说明用户名错误
        if(user==null){
            //抛出账号异常（用户名错误）
            throw new AccountException();
        }
         //第一个参数  会员信息   第2参数 加密密码  第3参数 ByteSource  盐值封装的ByteSource    第4个 当前realm的名称
        return new SimpleAuthenticationInfo(user,user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),this.getName());
    }


}
